package com.paranoidvulture.javaEngine.Utilities;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;


public class Button extends ControlBase {

	private Rectangle2D rec;
	private Color bgColor, fgColor;
	private int fontSize = 10;
	private String fontType = "Serif";
	private float txtPosX, txtPosY;
	private List<ButtonListener> bListen;
	
	public float getTxtPosX(){
		return this.txtPosX;
	}
	
	public void addBListeners(ButtonListener b) {
		bListen.add(b);
	}
	
	public float getTxtPosY(){
		return this.txtPosY;
	}
	
	public void setTxtPosX(float x){
		this.txtPosX = x;
	}
	
	public void setTxtPosY(float y){
		this.txtPosY = y;
	}
	
	public Rectangle2D getRectangle() {
		return rec;
	}
	
	public void setActualTxtPos(double fontLength){
		float x = this.getPosX();
		float y = this.getPosY();
		float start = (float)fontLength/2;
		this.setTxtPosX(x + ((float)this.getWidth() * .5f) - start);
		this.setTxtPosY(y + ((float)this.getHeight() *.75f));
	}
	
	public void init(String title) {
		this.setWidth(100);
		this.setHeight(32);		
		this.setName(title);
		this.bgColor = Color.red;
		bListen = new ArrayList<ButtonListener>();
	}

	public void update(long timePassed) {
		rec = new Rectangle2D.Double((int)this.getPosX(), 
				(int)this.getPosY(), this.getWidth(), this.getHeight());
	}
	
	public void draw(Graphics2D g){
		if (this.getActive()){
			//Use Fill to have a nice backdrop.
			g.setColor(bgColor);
			g.fill(rec);
			g.setColor(fgColor);
			g.draw(rec);
			g.setColor(Color.black);
			Font font = new Font(this.fontType, Font.PLAIN, this.fontSize);
			Rectangle2D f = font.getStringBounds(this.getName(), g.getFontRenderContext());
			setActualTxtPos(f.getWidth());
			g.setFont(font);
			g.drawString(this.getName(), (int)this.getTxtPosX(), (int)this.getTxtPosY());
		}
	}
	
	@Override
	public void mouseClicked(MouseEvent e) {
		if (rec.contains(e.getX(), e.getY())) {
			bgColor = Color.orange;
			for (ButtonListener b : bListen) {
				b.buttonClick(this);
			}
		}
	}

	@Override
	public void mouseEntered(MouseEvent e) {
	
	}

	@Override
	public void mouseExited(MouseEvent e) {

	}

	@Override
	public void mousePressed(MouseEvent e) {

	}

	@Override
	public void mouseReleased(MouseEvent e) {

	}

	@Override
	public void mouseDragged(MouseEvent arg0) {

	}

	@Override
	public void mouseMoved(MouseEvent e) {
		if (rec.contains(e.getX(), e.getY())) {
			fgColor = Color.blue;
		} else {
			fgColor = Color.red;
			bgColor = Color.red;
		}
	}

	@Override
	public void keyPressed(KeyEvent arg0) {
	
	}

	@Override
	public void keyReleased(KeyEvent arg0) {

	}

	@Override
	public void keyTyped(KeyEvent arg0) {

	}

}
